package nl.will.dirstat;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

public class Visualizer {
	private int sumXDraw = 0;

	private long sumBytesSizeDraw = 0;

	private int sumOfDirsToShow = 10;

	private Directory directory;

	private static String SPACES = null;

	private static final char PRINT_CHAR = '%';

	private final static int SUM_OF_SPACES = 40;

	static {
		char[] chars = new char[SUM_OF_SPACES];
		for (int i = 0; i < chars.length; i++) {
			chars[i] = ' ';
		}
		SPACES = new String(chars);
	}

	private final static Comparator FILE_LENGHT_COMPARATOR = new Comparator() {

		public int compare(Object o1, Object o2) {
			if ((o1 instanceof File) && (o2 instanceof File)) {
				File file1 = (File) o1;
				File file2 = (File) o2;

				if (file1.length() > file2.length()) {
					return -1;
				} else if (file1.length() < file2.length()) {
					return 1;
				} else {
					return 0;
				}

			}
			throw new RuntimeException("Object are not of type File");
		}
	};

	public Visualizer(Directory directory, int sumOfDirsToShow) {
		this.sumOfDirsToShow = sumOfDirsToShow;
		this.directory = directory;
	}

	public Visualizer(Directory directory) {
		this.directory = directory;
	}

	public void printDirectoryToConsole() {
		System.out.println(directory);

		long totalSize = directory.length();
		File[] files = directory.listFiles();
		Arrays.sort(files, FILE_LENGHT_COMPARATOR);

		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (i < sumOfDirsToShow) {
				long sumOfX = (file.length() * 100) / totalSize;
				sumBytesSizeDraw = sumBytesSizeDraw + file.length();
				print(file.getName(), file.length(), sumOfX);
			}

		}
		if (sumXDraw < 100) {

			print("OTHER", totalSize - sumBytesSizeDraw, 100 - sumXDraw);

		}

	}

	private void print(String name, long bytesSize, long sumOfX) {
		if (sumOfX == 0) {
			sumOfX = 1;
		}
		StringBuffer console = new StringBuffer((" " + name + " " + bytesSize + SPACES).substring(0, SUM_OF_SPACES));
		for (int j = 0; j < sumOfX; j++) {
			console.append(PRINT_CHAR);
			this.sumXDraw++;
		}
		System.out.println(console);
	}

}
